package com.hfi.restful.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hfi.restful.response.Response;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ChangLiang
 * @date 2019/9/5
 */
@Component
@Order
public class ExceptionHandlerFilter implements Filter {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (RuntimeException e) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Response resp = new Response();
            resp.setErrorcode("500");
            resp.setValue("服务器出错啦");

            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(objectMapper.writeValueAsString(resp));
        }
    }

    @Override
    public void destroy() {

    }
}
